package com.uduemc.jcms.common.component.render;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.uduemc.jcms.config.render.JcmsRenderConfig;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;

@Component
public class JcmsRender {

	@Autowired
	private JcmsRenderConfig jcmsRenderConfig;

	public String tempPath(String key) {
		String datePath = jcmsRenderConfig.filepath() + File.separator + "temp" + File.separator + DateUtil.format(LocalDateTimeUtil.now(), "yyyy-MM");
		String tempPath = datePath + File.separator + SecureUtil.md5(key);
		return tempPath;
	}

	public String cacheGet(String key) {
		String tempPath = tempPath(key);
		File tempFile = new File(tempPath);
		if (!tempFile.isFile()) {
			return "";
		}
		String content = FileUtil.readUtf8String(tempFile);
		return content;
	}

	public void cacheSet(String key, String content) {
		String tempPath = tempPath(key);
		File tempFile = new File(tempPath);
		if (!tempFile.getParentFile().isDirectory()) {
			FileUtil.mkdir(tempFile.getParentFile());
		}
		FileUtil.writeString(content, tempFile, "UTF-8");
	}
}
